package plugins.AI;

import com.alibaba.fastjson.JSONObject;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.gpt.IGPTAction;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;


import java.util.HashMap;
import java.util.Map;


/**
 * 动态表单插件
 */
public class DietAnalysisAction implements IGPTAction {
    // 实体标识
    private static final String USER_DATA_ENTITY = "dcb4_userdata";
    private static final String ORDER_ENTITY = "dcb4_order_history";
    private static final String DISH_ENTITY = "dcb4_dishes";

    @Override
    public Map<String, String> invokeAction(String action, Map<String, String> params) {
        // 1. 获取当前用户信息
        String username = RequestContext.get().getUserName();

        // 2. 查询用户健康数据
        JSONObject userData = getUserHealthData(username);

        // 3. 查询用户历史订单
        JSONObject orderHistory = getOrderHistory(username);

        // 4. 查询菜品营养数据
        JSONObject dishNutrition = getDishNutrition();

        // 5. 组装大模型输入数据
        JSONObject aiInput = new JSONObject();
        aiInput.put("user", userData);
        aiInput.put("orders", orderHistory);
        aiInput.put("dishes", dishNutrition);

        // 6. 返回结构化数据
        Map<String, String> result = new HashMap<>();
        result.put("diet_data", aiInput.toJSONString());
        return result;
    }

    private JSONObject getUserHealthData(String username) {
        QFilter filter = new QFilter("name", "=", username);
        DynamicObject user = QueryServiceHelper.queryOne(
                USER_DATA_ENTITY,
                "name,dcb4_height,dcb4_weight,dcb4_bmi",
                new QFilter[]{filter}
        );

        return new JSONObject()
                .fluentPut("height", user.get("dcb4_height"))
                .fluentPut("weight", user.get("dcb4_weight"))
                .fluentPut("bmi", user.get("dcb4_bmi"));
    }

    private JSONObject getOrderHistory(String username) {
        QFilter filter = new QFilter("dcb4_buyer", "=", username);
        DynamicObjectCollection orders = QueryServiceHelper.query(
                ORDER_ENTITY,
                "billno,dcb4_buyer,createdate",
                new QFilter[]{filter}
        );

        JSONObject result = new JSONObject();
        orders.forEach(order -> {
            result.put(order.getString("billno"), new JSONObject()
                    .fluentPut("buyer", order.get("dcb4_buyer"))
                    .fluentPut("date", order.getDate("createdate"))
            );
        });
        return result;
    }

    private JSONObject getDishNutrition() {
        DynamicObjectCollection dishes = QueryServiceHelper.query(
                DISH_ENTITY,
                "number,name,dcb4_nutritionfactslist.dcb4_nutrient,dcb4_nutritionfactslist.dcb4_value",
                null
        );

        JSONObject result = new JSONObject();
        dishes.forEach(dish -> {
            JSONObject nutrients = new JSONObject();
            dish.getDynamicObjectCollection("dcb4_nutritionfactslist").forEach(n -> {
                nutrients.put(n.getString("dcb4_nutrient"), n.get("dcb4_value"));
            });
            result.put(dish.getString("number"), new JSONObject()
                    .fluentPut("name", dish.get("name"))
                    .fluentPut("nutrients", nutrients)
            );
        });
        return result;
    }
}